package cn.bdqn.asecu.service;

import cn.bdqn.asecu.config.FileHelper;
import cn.bdqn.asecu.config.FileStorageProperties;
import cn.bdqn.pojo.Know;
import cn.bdqn.repository.Asecu_AuditBaseRepository;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;

import static javafx.scene.input.KeyCode.H;

/**
 * 审计知识库service
 */
@Service
public class AsecuAuditBaseService {

    private final Path uploadPath;

    public AsecuAuditBaseService(FileStorageProperties fileStorageProperties) {
        this.uploadPath = Paths.get(FileHelper.getUploadPath(fileStorageProperties), new String[0]).toAbsolutePath()
                .normalize();
        try {
            Files.createDirectories(this.uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @Resource
    Asecu_AuditBaseRepository asecu_auditBaseRepository;

    public List<Know> getData() {
        List<Know> knows = asecu_auditBaseRepository.findAll();
        return knows;
    }

    /**
     * 存储文件
     * @param file
     * @return
     */
    @Transactional
    public Know storeFile(MultipartFile file, String keypoints,String name) {

        //文件原名称
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        Know know = null;
        try {
            if (fileName.contains("..")) {
                System.out.println("错误");
            }
            //文件格式
            String fileExtensionName = FileHelper.getExtFromFileName(fileName);
            System.out.println(fileExtensionName);
            //新文件名称
            String randomFileName = FileHelper.createRandomFileName(fileExtensionName);
            System.out.println(randomFileName);
            Path targetLocation = Paths.get(this.uploadPath + File.separator + randomFileName, new String[0]);
            System.out.println(targetLocation);
            //储存到本地
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            know = new Know(keypoints,randomFileName,new Date(),"1",this.uploadPath.toString(),fileExtensionName,name ,file.getSize(),fileName);

            this.asecu_auditBaseRepository.save(know);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return know;
    }

    /**
     * 根据id获取文件信息
     * @param id
     * @return
     */
    public Know getFileInfoById(Long id) {
        Know know = this.asecu_auditBaseRepository.findById(id.intValue()).get();
        return know;
    }

    /**
     * 根据id加载文件资源
     * @param id
     * @return
     */
    public org.springframework.core.io.Resource loadFileAsResource(Long id) {
        try {
            Know know = getFileInfoById(id);
            Path filePath = Paths.get(know.getFilePath() + File.separator + know.getFileName(), new String[0])
                    .normalize();
            org.springframework.core.io.Resource resource = (org.springframework.core.io.Resource) new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return resource;
            }
        } catch (NoSuchElementException | MalformedURLException ex3) {
        }
        return null;
    }

    /**
     * 删除文件
     * @param id
     * @return
     */
    @Transactional
    public Boolean removeFile(Integer id) {
        org.springframework.core.io.Resource resource = this.loadFileAsResource(id.longValue());
        try {
            this.asecu_auditBaseRepository.deleteById(id);
            return resource.getFile().delete();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
